<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Maatwebsite\Excel\Facades\Excel;
use OSS\OssClient;
use OSS\Core\OssException;
use App\Models\RoleUser;
use App\Http\Controllers\Api\ApartmentApplicationExports;

class ApartmentApplicationController extends Controller
{
    public function editApartmentApplication(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();

        if (!isset($request_data['unit_name']) || !$request_data['unit_name']) {
            return response()->json(['code' => 0, 'message' => '单位名称为必填项']);
        }
        if (!isset($request_data['unit_name_range']) || !$request_data['unit_name_range']) {
            return response()->json(['code' => 0, 'message' => '单位地区范围为必填项']);
        }
        // if (!isset($request_data['corporate_compliance']) || !$request_data['corporate_compliance']) {
        //     return response()->json(['code' => 0, 'message' => '法人代表为必填项']);
        // }
        // if (!isset($request_data['organization_code']) || !$request_data['organization_code']) {
        //     return response()->json(['code' => 0, 'message' => '组织机构代码为必填项']);
        // }
        // if (!isset($request_data['unit_nature']) || !$request_data['unit_nature']) {
        //     return response()->json(['code' => 0, 'message' => '单位性质为必填项']);
        // }
        if (!isset($request_data['field']) || !$request_data['field']) {
            return response()->json(['code' => 0, 'message' => '所属领域为必填项']);
        }
        if (!isset($request_data['contact_name']) || !$request_data['contact_name']) {
            return response()->json(['code' => 0, 'message' => '联系人为必填项']);
        }
        if (!isset($request_data['contact_phone']) || !$request_data['contact_phone']) {
            return response()->json(['code' => 0, 'message' => '联系电话为必填项']);
        }
        if (!isset($request_data['contact_address']) || !$request_data['contact_address']) {
            return response()->json(['code' => 0, 'message' => '联系地址为必填项']);
        }
        if (!isset($request_data['talent_category']) || !$request_data['talent_category']) {
            return response()->json(['code' => 0, 'message' => '人才类别为必填项']);
        }
        if (!isset($request_data['real_name']) || !$request_data['real_name']) {
            return response()->json(['code' => 0, 'message' => '真实姓名为必填项']);
        }
        if (!isset($request_data['phone']) || !$request_data['phone']) {
            return response()->json(['code' => 0, 'message' => '联系电话为必填项']);
        }
        if (!isset($request_data['idcard']) || !$request_data['idcard']) {
            return response()->json(['code' => 0, 'message' => '身份证为必填项']);
        }
        if (!isset($request_data['sex']) || !$request_data['sex']) {
            return response()->json(['code' => 0, 'message' => '性别为必填项']);
        }
        if (!isset($request_data['birthday']) || !$request_data['birthday']) {
            return response()->json(['code' => 0, 'message' => '出生日期为必填项']);
        }
        if (!isset($request_data['nationality']) || !$request_data['nationality']) {
            return response()->json(['code' => 0, 'message' => '民族为必填项']);
        }
        if (!isset($request_data['birthplace']) || !$request_data['birthplace']) {
            return response()->json(['code' => 0, 'message' => '籍贯为必填项']);
        }
        // if (!isset($request_data['social_security']) || !$request_data['social_security']) {
        //     return response()->json(['code' => 0, 'message' => '社保参保地为必填项']);
        // }
        if (!isset($request_data['come_work_time']) || !$request_data['come_work_time']) {
            return response()->json(['code' => 0, 'message' => '来区工作时间为必填项']);
        }
        if (!isset($request_data['education']) || !$request_data['education']) {
            return response()->json(['code' => 0, 'message' => '学历为必填项']);
        }
        if (!isset($request_data['degree']) || !$request_data['degree']) {
            return response()->json(['code' => 0, 'message' => '学位为必填项']);
        }
        if (!isset($request_data['job_title']) || !$request_data['job_title']) {
            return response()->json(['code' => 0, 'message' => '职称为必填项']);
        }
        if (!isset($request_data['position']) || !$request_data['position']) {
            return response()->json(['code' => 0, 'message' => '职务为必填项']);
        }
        if (!isset($request_data['work_time']) || !$request_data['work_time']) {
            return response()->json(['code' => 0, 'message' => '任职时间为必填项']);
        }
        if (!isset($request_data['house_situation']) || !$request_data['house_situation']) {
            return response()->json(['code' => 0, 'message' => '住房情况为必填项']);
        }
        if (!isset($request_data['address']) || !$request_data['address']) {
            return response()->json(['code' => 0, 'message' => '详细地址为必填项']);
        }
        if (!isset($request_data['lease_period_start_time']) || !$request_data['lease_period_start_time']) {
            return response()->json(['code' => 0, 'message' => '开始租房时间为必填项']);
        }
        if (!isset($request_data['lease_period_end_time']) || !$request_data['lease_period_end_time']) {
            return response()->json(['code' => 0, 'message' => '结束租房时间为必填项']);
        }
        // if (!isset($request_data['study_work_experience']) || !$request_data['study_work_experience']) {
        //     return response()->json(['code' => 0, 'message' => '学习与工作经历为必填项']);
        // }
        if (!isset($request_data['photo']) || !$request_data['photo']) {
            return response()->json(['code' => 0, 'message' => '照片为必填项']);
        }
        if (!isset($request_data['marriage_childbirth']) || !$request_data['marriage_childbirth']) {
            return response()->json(['code' => 0, 'message' => '婚育情况为必填项']);
        }
        if (trim($request_data['marriage_childbirth']) != '未婚') {
            if (!isset($request_data['spouse_name']) || !$request_data['spouse_name']) {
                return response()->json(['code' => 0, 'message' => '配偶名称为必填项']);
            }
            if (!isset($request_data['spouse_idcard']) || !$request_data['spouse_idcard']) {
                return response()->json(['code' => 0, 'message' => '配偶身份证为必填项']);
            }
            if (!isset($request_data['spouse_contact']) || !$request_data['spouse_contact']) {
                return response()->json(['code' => 0, 'message' => '配偶联系方式为必填项']);
            }
            if (!isset($request_data['spouse_work_unit']) || !$request_data['spouse_work_unit']) {
                return response()->json(['code' => 0, 'message' => '配偶工作单位为必填项']);
            }
            if (!isset($request_data['spouse_house_situation']) || !$request_data['spouse_house_situation']) {
                return response()->json(['code' => 0, 'message' => '配偶住房情况为必填项']);
            }
        }
        if (!isset($request_data['relevant_information']) || !$request_data['relevant_information']) {
            return response()->json(['code' => 0, 'message' => '相关资料图片为必填项']);
        }

        $idcard = $request_data['idcard'];
        $data = $request_data;
        unset($data['user']);
        $result = [];
        if (!isset($request_data['apartment_application_id']) || !$request_data['apartment_application_id']) {
            $application_info = DB::table('apartment_application')->where('phone', $request_data['phone'])->first();
            if ($application_info) {
                return response()->json(['code' => 0, 'message' => '你已经申请公寓，可点击查询查看申请进度']);
            }
            $data['source'] = 1;
            DB::beginTransaction();
            try {
                $user_info = DB::table('member')->where('mobile', $data['phone'])->first();
                if ($user_info) {
                    $user_id = $user_info->id;
                } else {
                    $user_id = DB::table('member')->insertGetId(array('mobile' => $data['phone'], 'name' => $data['real_name'], 'user_id' => 1, 'created_at' => date('Y-m-d H:i:s', time())));
                }
                $data['user_id'] = $user_id;
                $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[50]['regulation']);
                $message = new MessageController();
                foreach ($user_ids as $key => $uid) {
                    $message->addMessage($uid->user_id, 50, '公寓申请待审核');
                }

                if ($user_id && DB::table('apartment_application')->insert($data)) {
                    DB::commit();
                    return response()->json(['code' => 1, 'message' => '申请成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code' => 0, 'message' => '申请失败']);
                }
            }  catch (Exception $e) {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '申请失败']);
            }
        } else {
            $application_info = DB::table('apartment_application')->where('apartment_application_id', $request_data['apartment_application_id'])->first();
            // 当除了审核通过之外的情况修改重置状态为待初审
            //审批状态（0：待初审，1：待复审，2：初审不通过，3：初审驳回，4：复审通过，5：审批不通过，6：复审驳回）
            if (in_array($application_info->approval_status, [2,3,5,6])) {
                $data['approval_status'] = 0;
                $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[50]['regulation']);
                $message = new MessageController();
                foreach ($user_ids as $key => $uid) {
                    $message->addMessage($uid->user_id, 50, '公寓申请待审核');
                }
            }
            if (DB::table('apartment_application')->where('apartment_application_id', trim($data['apartment_application_id']))->update($data)) {
                $result['code'] = 1;
                $result['message'] = '修改成功';
            } else {
                $result['code'] = 0;
                $result['message'] = '修改失败或内容没作修改';
            }
        }

        return response()->json($result);
    }

    public function ApartmentApplicationExports(Request $request){
        ini_set('memory_limit','500M');
        set_time_limit(0);
        return Excel::download(new ApartmentApplicationExports, '公寓服务会员名单.xlsx');
    }

    public function apartmentApplicationImport(Request $request){
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();
        if (!isset($request_data['file_path']) || !$request_data['file_path']) {
            return response()->json(['code' => 0, 'message' => '导入文件路径为必填项']);
        }
        $file_path = $request_data['file_path'];

        if (is_file(app_path().DIRECTORY_SEPARATOR.'Libraries'.DIRECTORY_SEPARATOR.'Aliyun-oss'.DIRECTORY_SEPARATOR.'autoload.php')) {
            require_once app_path().DIRECTORY_SEPARATOR.'Libraries'.DIRECTORY_SEPARATOR.'Aliyun-oss'.DIRECTORY_SEPARATOR.'autoload.php';
        }

        try {
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            $accessKeyId = "LTAIKSeZmyYSdn4Z";
            $accessKeySecret = "k33JSmnxYYybzVMTzrubP3sJIBOKc8";
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
            // 存储空间名称
            $bucket= "rcfwlm-data";
            // object 表示您在下载文件时需要指定的文件名称，如abc/efg/123.jpg。
            $object = substr($file_path, 48);
            $file_array = explode('/', $file_path);
            // 指定文件下载路径。
            $localfile = "../storage/". $file_array[count($file_array) - 1];
            $options = array(
                OssClient::OSS_FILE_DOWNLOAD => $localfile
            );
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->getObject($bucket, $object, $options);
        } catch (OssException $e) {
            echo $e->getMessage();
            return response()->json(['code' => 0, 'message' => '获取导入文件失败']);
        }
        $datas = Excel::toArray(new ApartmentApplicationImport, $localfile);
        $field_list  = ['unit_name','corporate_compliance','organization_code','unit_nature','field','contact_name','contact_phone','contact_address','talent_category','real_name','phone','idcard','sex','birthday','nationality','birthplace','social_security','come_work_time','education','degree','job_title','position','work_time','house_situation','address','lease_period_start_time','lease_period_end_time','study_work_experience','photo','marriage_childbirth','spouse_name','spouse_idcard','spouse_contact','spouse_work_unit','spouse_house_situation','relevant_information', 'unit_name_range','honors','honor_level'];
        if (isset($datas[0])) {
            foreach ($datas[0] as $key => $value) {
                if ($key > 1) {
                    $data = array(
                        'source' => 1
                    );
                    foreach ($field_list as $index => $field) {
                        $data[$field] = $value[$index];
                    }
                    unset($data['photo']);
                    unset($data['relevant_information']);
                    if ($data['marriage_childbirth'] == '未婚') {
                        unset($data['spouse_name']);
                        unset($data['spouse_idcard']);
                        unset($data['spouse_contact']);
                        unset($data['spouse_work_unit']);
                        unset($data['spouse_house_situation']);
                    }
                    DB::beginTransaction();
                    try {
                        $user = DB::table('member')->where('mobile', $data['phone'])->first();
                        $user_id = 0;
                        if (!$user) {
                            $user_id = DB::table('member')->insertGetId(array('mobile' => $data['phone'], 'name' => $data['real_name'], 'user_id' => 1, 'created_at' => date('Y-m-d H:i:s', time())));
                            if (!$user_id) {
                                DB::rollBack();
                                continue;
                            }
                        } else {
                            $user_id = $user->id;
                        }
                        $data['user_id'] = $user_id;
                        $application_info = DB::table('apartment_application')->where('phone', $data['phone'])->first();
                        if (!$application_info) {
                            if(!DB::table('apartment_application')->insertGetId($data)) {
                                DB::rollBack();
                                continue;
                            }
                        }
                        
                        DB::commit();
                    }  catch (Exception $e) {
                        DB::rollBack();
                    }
                }
            }
        }
        
        // 删除下载的EXCEL文件
        unlink($localfile);
        return response()->json(['code' => 1, 'message' => '导入成功']);
    }

    public function apartmentApplicationInfo(Request $request, $apartment_application_id) {
        if (!$request->isMethod('GET')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }
        $response_data = DB::table('apartment_application')->where('apartment_application_id', $apartment_application_id)->first();
        $response_data = $response_data ? $response_data : array();
        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function apartmentApplicationList(Request $request) {
        if (!$request->isMethod('GET')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();
        $user_keywords = '';
        $approval_status = '';
        $approval_start_time = '';
        $approval_end_time = '';
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['approval_status'])) {
            $approval_status = $request_data['approval_status'];
        }
        if (isset($request_data['approval_start_time'])) {
            $approval_start_time = $request_data['approval_start_time'];
        }
        if (isset($request_data['approval_end_time'])) {
            $approval_end_time = $request_data['approval_end_time'];
        }
        $page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }
        $sql = "SELECT apartment_application_id, real_name, phone, idcard, unit_name, approval_status, source,file, add_time FROM rcjh_apartment_application WHERE status = 1";
        if ($user_keywords) {
            $sql .= " AND (real_name LIKE '%$user_keywords%' OR phone LIKE '%$user_keywords%')";
        }
        if ($approval_start_time) {
            if ($approval_status < 2) {
                $sql .= " AND add_time > '$approval_start_time'";
            } else {
                $sql .= " AND approval_time > '$approval_start_time'";
            }
        }
        if ($approval_end_time) {
            if ($approval_status < 2) {
                $sql .= " AND add_time < '$approval_end_time'";
            } else {
                $sql .= " AND approval_time < '$approval_end_time'";
            }
        }
        // 待初审
        if ($approval_status == 1) {
            $sql .= " AND approval_status = 0";
        // 待复审
        } elseif ($approval_status == 2) {
            $sql .= " AND approval_status = 1";
        // 审核通过
        } elseif ($approval_status == 3) {
            $sql .= " AND approval_status = 4";
        // 审核不通过
        } elseif ($approval_status == 4) {
            $sql .= " AND approval_status in (2, 5)";
        // 驳回
        } elseif ($approval_status == 5) {
            $sql .= " AND approval_status in (3, 6)";
        }
        if ($approval_status < 2) {
            $sql .= " ORDER BY add_time DESC";
        } else {
            $sql .= " ORDER BY approval_time DESC";
        }
        $response_data = DB::table(DB::raw("($sql limit 9999999) as apartment_application"))->Paginate($page_size);
        foreach ($response_data as $key => $value) {
            $response_data[$key]->stage = '';
            $response_data[$key]->approval_result = '';
            $response_data[$key]->remark = '';
            $response_data[$key]->approval_time = '';
            $response_data[$key]->approval_name = '';
            $response_data[$key]->status = 1;
            if (($value->approval_status == 3 || $value->approval_status == 6) && $value->source == 1) {
                $response_data[$key]->status = 2;
            }
            $approval_info = DB::table('apartment_approval_records')->where('apartment_application_id', $value->apartment_application_id)->orderby('apartment_approval_record_id', 'DESC')->first();
            if ($approval_info && $value->approval_status > 0) {
                $response_data[$key]->stage = $approval_info->stage;
                $response_data[$key]->approval_result = $approval_info->approval_result;
                $response_data[$key]->remark = $approval_info->remark;
                $response_data[$key]->approval_time = $approval_info->add_time;
                $approval_name = DB::table('admins')->where('id', $approval_info->approval_uid)->value('name');
                $response_data[$key]->approval_name = $approval_name ? $approval_name : '';
                if (($value->approval_status == 2 || $value->approval_status == 5) && $value->source == 1) {
                    if (date('Y-m-d H:i:s') > date("Y-m-d H:i:s",strtotime("+$approval_info->expired_days day",strtotime($approval_info->add_time)))) {
                        $response_data[$key]->status = 2;
                    }
                }
            }
        }

        return response()->json(['code' => 1, 'data' => $response_data]);
    }

    public function apartmentApplicationApproval(Request $request) {
        $request_data = $request->input();

        if (!isset($request_data['apartment_application_id']) || !$request_data['apartment_application_id']) {
            return response()->json(['code' => 0, 'message' => '公寓申请ID为必填项']);
        }
        if (!isset($request_data['approval_result'])) {
            return response()->json(['code' => 0, 'message' => '审核结果为必填项']);
        }
        $expired_days = 0;
        // TODO 验证审核结果值
        if ($request_data['approval_result'] != 1 && (!isset($request_data['remark']) || !$request_data['remark'])) {
            return response()->json(['code' => 0, 'message' => '备注为必填项']);
        }

        // 审核不通过过期天数为必填
        if ($request_data['approval_result'] == 0 && (!isset($request_data['expired_days']) || !$request_data['expired_days'])) {
            return response()->json(['code' => 0, 'message' => '过期天数必须大于0']);
        }
        if ($request_data['approval_result'] == 0) {
            $expired_days = $request_data['expired_days'];
        }

        $application_info = DB::table('apartment_application')->where('apartment_application_id', $request_data['apartment_application_id'])->where('status', 1)->first();
        $stage = 1;
        if (!$application_info) {
            return response()->json(['code' => 0, 'message' => '审核记录错误']);
        }
        if (!in_array($application_info->approval_status, [0, 1])) {
            return response()->json(['code' => 0, 'message' => '该申请当前状态不能进行审核']);
        }
        if ($application_info->approval_status > 0) {
            $stage = 2;
            if(!DB::select("SELECT u.user_id FROM rcjh_permissions p, rcjh_permission_role r, rcjh_role_user u WHERE p.id = r.permission_id AND r.role_id = u.role_id AND r.permission_id =".config('message')[51]['regulation']." AND u.user_id = ". $request_data['user']['uid'])){
                return response()->json(['code'=>'0','message'=>'您无权限进行此操作']);
            }
        } else {
            if(!DB::select("SELECT u.user_id FROM rcjh_permissions p, rcjh_permission_role r, rcjh_role_user u WHERE p.id = r.permission_id AND r.role_id = u.role_id AND r.permission_id =".config('message')[50]['regulation']." AND u.user_id = ". $request_data['user']['uid'])){
                return response()->json(['code'=>'0','message'=>'您无权限进行此操作']);
            }
        }

        DB::beginTransaction();
        try {
            $apartment_approval_records_data = array(
                'apartment_application_id' => $request_data['apartment_application_id'],
                'stage' => $stage,
                'approval_result' => $request_data['approval_result'],
                'approval_uid' => $request_data['user']['uid'],
                'remark' => $request_data['remark'],
                'expired_days' => $expired_days
            );
            $approval_status = 0;
            if ($request_data['approval_result'] == 0) {
                $approval_status = 2;
            } else if ($request_data['approval_result'] == 1) {
                $approval_status = 1;
            } else if ($request_data['approval_result'] == 2) {
                $approval_status = 3;
            }
            if ($stage == 1) {
                // 初审通过通知管理员
                if ($request_data['approval_result'] == 1) {
                    $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[51]['regulation']);
                    $message = new MessageController();
                    foreach ($user_ids as $key => $uid) {
                        $message->addMessage($uid->user_id, 51, '公寓申请初审通过待复审');
                    }
                }
                if ($request_data['approval_result'] == 0) {
                    (new MessageController())->addMessage($application_info->user_id, 54, '您的公寓申请已初审不通过');
                } else if ($request_data['approval_result'] == 1) {
                    (new MessageController())->addMessage($application_info->user_id, 53, '您的公寓申请已初审通过');
                } else if ($request_data['approval_result'] == 2) {
                    (new MessageController())->addMessage($application_info->user_id, 55, '您的公寓申请已初审驳回');
                }
            } else if ($stage == 2) {
                // 复审通过通知管理员
                if ($request_data['approval_result'] == 1) {
                    $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[52]['regulation']);
                    $message = new MessageController();
                    foreach ($user_ids as $key => $uid) {
                        $message->addMessage($uid->user_id, 52, '复审通过，待房源分配');
                    }
                }
                if ($request_data['approval_result'] == 0) {
                    (new MessageController())->addMessage($application_info->user_id, 57, '您的公寓申请已复审不通过');
                } else if ($request_data['approval_result'] == 1) {
                    (new MessageController())->addMessage($application_info->user_id, 56, '您的公寓申请已复审通过');
                } else if ($request_data['approval_result'] == 2) {
                    (new MessageController())->addMessage($application_info->user_id, 58, '您的公寓申请已复审驳回');
                }
            }
            $approval_status = ($stage - 1) * 3 + $approval_status;
            if (DB::table('apartment_approval_records')->insert($apartment_approval_records_data) && DB::table('apartment_application')->where('apartment_application_id', $request_data['apartment_application_id'])->update(['approval_status' =>  $approval_status, 'approval_time' => date("Y-m-d H:i:s")])) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '处理成功']);
            } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '处理失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '处理失败']);
        }
    }

    public function deleteApartmentApplication(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();
        if (!isset($request_data['apartment_application_id']) || !$request_data['apartment_application_id']) {
            return response()->json(['code' => 0, 'message' => '公寓申请ID为必填项']);
        }
        $apartment_application_id = $request_data['apartment_application_id'];
        if (DB::table('apartment_application')->where('apartment_application_id', trim($apartment_application_id))->update(['status' => 0])) {
            $result['code'] = 1;
            $result['message'] = '删除成功';
        } else {
            $result['code'] = 0;
            $result['message'] = '删除失败或该数据已删除';
        }
        return response()->json($result);
    }

    public function applicationApprovalList(Request $request) {
        if (!$request->isMethod('GET')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();
        $user_keywords = '';
        $approval_status = '';
        $approval_start_time = '';
        $approval_end_time = '';
        if (isset($request_data['user_keywords'])) {
            $user_keywords = $request_data['user_keywords'];
        }
        if (isset($request_data['approval_status'])) {
            $approval_status = $request_data['approval_status'];
        }
        if (isset($request_data['approval_start_time'])) {
            $approval_start_time = $request_data['approval_start_time'];
        }
        if (isset($request_data['approval_end_time'])) {
            $approval_end_time = $request_data['approval_end_time'];
        }
        $page_size = 10;
        if (isset($request_data['page_size'])) {
            $page_size = $request_data['page_size'];
        }
        $sql = "SELECT rac.apartment_approval_record_id, ra.real_name, ra.phone, ra.idcard, ra.unit_name, rac.stage, rac.approval_result, rac.approval_uid, rac.add_time as approval_time FROM rcjh_apartment_application ra, rcjh_apartment_approval_records rac WHERE ra.apartment_application_id = rac.apartment_application_id AND ra.status = 1";
        if ($user_keywords) {
            $sql .= " AND (ra.real_name LIKE '%$user_keywords%' OR ra.phone LIKE '%$user_keywords%')";
        }
        if ($approval_start_time) {
            $sql .= " AND rac.add_time > '$approval_start_time'";
        }
        if ($approval_end_time) {
            $sql .= " AND rac.add_time < '$approval_end_time'";
        }
        // 初审通过待复审
        if ($approval_status == 1) {
            $sql .= " AND rac.stage = 1 AND rac.approval_result = 1";
        // 审核通过
        } elseif ($approval_status == 2) {
            $sql .= " AND rac.stage = 2 AND rac.approval_result = 1";
        // 审核不通过
        } elseif ($approval_status == 3) {
            $sql .= " AND rac.approval_result = 0";
        // 初审驳回
        } elseif ($approval_status == 4) {
            $sql .= " AND rac.stage = 1 AND rac.approval_result = 2";
        // 复审驳回
        } elseif ($approval_status == 5) {
            $sql .= " AND rac.stage = 2 AND rac.approval_result = 2";
        }
        $sql .= " ORDER BY rac.add_time DESC";
        $response_data = DB::table(DB::raw("($sql limit 9999999) as apartment_application"))->Paginate($page_size);
        foreach ($response_data as $key => $value) {
            $approval_name = DB::table('admins')->where('id', $value->approval_uid)->value('name');
            $response_data[$key]->approval_name = $approval_name ? $approval_name : '';
        }

        return response()->json(['code' => 1, 'data' => $response_data]);
    }
}
